package be.tihh.mgmt.gui.tree;

import be.tihh.mgmt.gui.ComputerDetail;
import be.tihh.mgmt.gui.MainScreen;
import be.tihh.mgmt.gui.icontreenode.ComputerIcons;
import be.tihh.mgmt.gui.icontreenode.IconNode;
import be.tihh.mgmt.gui.xml.computers.Computer;
import be.tihh.mgmt.util.ComputerUtil;

import javax.swing.*;

public class SelectComputerAction implements Runnable {

    IconNode node;
    MainScreen mainScreen;

    public SelectComputerAction(IconNode node, MainScreen mainScreen) {
        this.node = node;
        this.mainScreen = mainScreen;
    }


    public void run() {

        //when selecting a computer in the tree
        if (node.getIconName() != null) {
            if (node.getIconName().startsWith(ComputerIcons.PREFIX)) {
                Computer computer = (Computer) node.getUserObject();
                mainScreen.refreshComputerDetail(computer);
//                System.out.println("set to unknown");
                ComputerDetail computerDetail = mainScreen.getComputerDetail();
                JLabel statusLabel = computerDetail.getStatusLabel();
                statusLabel.setText("Checking if computer is online...");
                statusLabel.setIcon(new ImageIcon("res\\icons\\time.png"));
                node.setIconName(ComputerIcons.COMPUTER_STATUS_UNKNOWN);
//                mainScreen.refreshTasksList(computer);
                repaintGui();


                //keep this code as last, since it freezes gui update
                if (ComputerUtil.isOnline(computer)) {
//                    System.out.println("computer is online");
                    statusLabel.setText("Online");
                    statusLabel.setIcon(new ImageIcon("res\\icons\\tick.png"));
                    node.setIconName(ComputerIcons.COMPUTER_STATUS_ON);
                } else {
//                    System.out.println("computer is offline");
                    statusLabel.setText("Offline");
                    statusLabel.setIcon(new ImageIcon("res\\icons\\cross.png"));
                    node.setIconName(ComputerIcons.COMPUTER_STATUS_OFF);
                }

            } else if (GuiTreeBuilder.FOLDER_ICON.equals(node.getIconName())) {
//                System.out.println("selected folder" + node.getUserObject());
            }
        }
        repaintGui();

    }

    private void repaintGui(){
        mainScreen.getMainPanel().getParent().repaint();
    }
}
